<template>
  <div class="register-container">
    <el-row>
      <el-col :span="12" :offset="6">
        <h2>欢迎注册</h2>
        <el-form ref="form" :model="formData" label-width="80px">
          <el-form-item label="用户名" prop="username" :rules="[
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ]">
            <el-input v-model="formData.username"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email" :rules="[
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
          ]">
            <el-input v-model="formData.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password" :rules="[
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ]">
            <el-input type="password" v-model="formData.password"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword" :rules="[
            { required: true, message: '确认密码不能为空', trigger: 'blur' },
            { validator: checkConfirmPassword, trigger: 'blur' }
          ]">
            <el-input type="password" v-model="formData.confirmPassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">注册</el-button>
          </el-form-item>
        </el-form>
        <p>已有账号？<a href="/login">登录</a></p>
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "RegisterView",
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
    };
  },
  methods: {
    onSubmit() {
      // 在这里进行注册逻辑处理，比如发送请求到后端
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('注册信息：', this.formData);
          this.axios.post("customer/registerCustomer", this.formData).then(res => {
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              this.$router.push("/login")
            }
          });
        } else {
          console.log('表单验证不通过');
        }
      });
    },
    checkConfirmPassword(rule, value, callback) {
      // 使用箭头函数确保 this 的正确指向
      const self = this;
      if (value === self.formData.password) {
        callback();
      } else {
        callback(new Error('两次输入密码不一致'));
      }
    }
  },
  created() {
    // 初始化逻辑可以放在这里，如果有的话
  }
};
</script>

<style scoped>
.register-container {
  background-color: #f5f5f5;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h2 {
  color: #333;
  text-align: center;
}
</style>